﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using ZingFrameworkCore.Common.Cache;
using ZingFrameworkCore.Common.Http;

namespace ZingFrameworkCore.Common
{
    public class IPAddressHelper
    {
        public static string Ip
        {
            get
            {
                var client = HttpContext.Current.Connection;
                var remoteIpAddress = client.RemoteIpAddress;
                if (remoteIpAddress != null)
                {
                    return remoteIpAddress.ToString();
                }
                return client.LocalIpAddress.ToString();
            }
        }
        public static IpLocation GetIpLocation(string ip)
        {
            var httpRequester = new HttpRequester();
            var result = new IpLocation() { Ip = Ip, Provice = "", City = "" };
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
                  try
            {
                var apiURL = $"https://whois.pconline.com.cn/ipJson.jsp?ip={Ip}&json=true";
                var response = httpRequester.Request(new HttpItem() { URL = apiURL }).ResponseData.ToObject<dynamic>();
                result.Provice = response.pro;
                result.City = response.city;

            }
            catch
            {

            }
            return result;
        }
    }

    public class IpLocation
    {
        public string Ip { get; set; }
        public string Provice { get; set; }
        public string City { get; set; }

        public override string ToString()
        {
            return $"{Provice}{City}";
        }
    }

}